// antd
import { Layout, Menu, Row, Col, Popconfirm } from 'antd';

// layout 组件
const { Header, Content, Footer, Sider } = Layout;

// 子菜单
const { SubMenu } = Menu

// css
import '../style/layout.less'

// react
import React, { useCallback, useEffect, useMemo, useState } from 'react'

// react-router V6 useNavigate 路由跳转
import { Route, Routes, useLocation, useNavigate, Navigate } from 'react-router-dom'

// route 渲染
import renderRoutes from '../utils/render-routes';
import Inventory from '../views/inventory/inventory';
import InventoryList from '../views/inventory/inventoryList';

// redux
import { useSelector, connect } from 'react-redux';
import { loginOutAction } from '../actions/user';

// 引入路由处理
import genPermissionRoutes from '../utils/gen-permission-routes';

// 组件
function layout(props) {

  // 获取 location 对象
  const location = useLocation()

  // 设置默认选择
  const [selectedKeys, setSelectedKeys] = useState([location.pathname.slice(1)])

  // 设置默认打开
  const [openKeys, setOpenKeys] = useState([(location.pathname.split('/'))[1]])

  // 保存权限路由
  const [Roles, setRoles] = useState([])

  // 获取 store 中的 token 对象
  const {token, id, info, roles} = useSelector((state) => state.user)

  // router 跳转
  const navigate = useNavigate()

  // 选中内容
  const [nowNavText, setNowNavText] = useState(() => forFind(props.child))

  // 菜单点击事件
  const menuClick = (item) => {
    navigate(item.key)
    setNowNavText(item.domEvent.target.innerHTML)
  }

  // useCallback 循环匹配

  // useMemo 缓存 导航组件
  const menu = useMemo(() => {

    const _renderMenu = (routes) => routes.map((route) => {
      if (!route.meta.noRender) {
        if (route.children) {
          return (
            <SubMenu key={route.to} title={route.meta.title} icon={route.meta.icon ? <route.meta.icon /> : null}>
              {_renderMenu(route.children)}
            </SubMenu>
          )
        } else {
          return (
            <Menu.Item key={route.to} icon={route.meta.icon ? <route.meta.icon /> : null} >
              {route.meta.title}
            </Menu.Item>
          )
        }
      }
    })
    return (
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={selectedKeys}
        defaultOpenKeys={openKeys}
        onClick={menuClick}
      >
        {_renderMenu(Roles)}
      </Menu>
    )
  }, [Roles])

  // 确认退出登录
  const confirm = useCallback(() => {
    props.out()
  }, [])

  // 处理路由
  useEffect(() => {
    // 如果有权限路由
    if (roles.length !== 0) {
      const res = genPermissionRoutes(roles, props.child)
      setRoles(res)
    }
  }, [roles])

  return token
    ?   (
      <>
        <Layout
          style={{height: '100%'}}
        >
          <Sider
            breakpoint="lg"
            collapsedWidth="0"
            onBreakpoint={(broken) => {
            }}
            onCollapse={(collapsed, type) => {
            }}
            className="siderBg"
          >
            <div className="logo" >
            logo
            </div>
            {
              menu
            }
          </Sider>
          <Layout>
            <Header className="site-layout-sub-header-background" style={{ padding: 0 }} >
              <Row>
                <Col span={6} offset={18} style={{textAlign: 'center'}}>
                  <img width={40} style={{borderRadius: '50%'}} src="https://bulma.io/images/placeholders/128x128.png" />
                  &emsp;
                  欢迎，<a href={'#/staffs/staffInfo?id=' + id} title="个人信息" style={{color: 'skyblue'}}>{info}</a>
                  &emsp;
                  <Popconfirm
                    title="是否退出登录"
                    placement="bottom"
                    onConfirm={confirm}
                    onCancel={() => {}}
                    okText="是"
                    cancelText="否"
                  >
                    <a href="#">退出登录</a>
                  </Popconfirm>
                </Col>
              </Row>
            </Header>
            <Content style={{ margin: '24px 16px 0' }}>
              <div >{nowNavText}</div>
              <div className="site-layout-background" style={{ padding: 24, minHeight: 360, height: '100%' }}>
                {
                  console.log(Roles),
                  renderRoutes(Roles)
                }
              </div>
            </Content>
            <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
          </Layout>
        </Layout>
      </>
    )
    :     <>
      <Routes>
        <Route path="*" element={<Navigate to="/login"/>}></Route>
      </Routes>
    </>
}

const forFind = (arr) => {
  let str = ''
  const hash = location.hash.slice(2)
  arr.forEach((val) => {
    if (hash.indexOf(val.to) === 0) {
      if (val.children) {
        str = forFind(val.children)
      } else {
        str = val.meta.title
      }
    }
  })
  return str
}

//
const mapStateToProps = null

const mapDispatchToProps = (dispatch) => ({
  out: () => dispatch(loginOutAction()),
})

export default connect(mapStateToProps, mapDispatchToProps)(layout)
